qui(function (require, exports, module) {
    Program.FileUpload = (function(){
        var $imgcrop = null;
        var constant = {
            uploadUrl: "http://upload.iqiyi.com/image_upload",
            requestUrl: "http://upload.iqiyi.com/request_image_upload",
            file: null
        }

        function getGallery() {
            var $gallery = $imgcrop.find(".gallery");
            return $gallery;
        }

        function getObjectURL(file) {
//            var url = null;
//            if (window.createObjectURL !== undefined) { // basic
//                url = window.createObjectURL(file);
//            } else if (window.URL !== undefined) { // mozilla(firefox)
//                url = window.URL.createObjectURL(file);
//            } else if (window.webkitURL !== undefined) { // webkit or chrome
//                url = window.webkitURL.createObjectURL(file);
//            }
//            return url;
            return Com.file.getObjectURL(file);
        }

        function startUpload(file) {
            var imgsrc, $imgdiv, $bardiv;
            file.uid = Com.string.createUUID();
            imgsrc = getObjectURL(file);
            $bardiv = $('<div class="progress progress-info"><div class="bar" style="width: 0%" /></div>');
            $imgdiv = $('<img class="loading" src="' + imgsrc + '" />');
            $imgdiv.data('loading', true).load(function (e) {
                Com.Image.procThumbnail($(this), 128, 80);
                $(this).unbind('load');
            });
            var $gallery = getGallery();
            $gallery.append($('<li class="item img-' + file.uid + '" />').append($imgdiv, $bardiv));
        }

        function qichuanRequestFile(options, callback) {
            options = options || {};
            constant.file = options.file;
            var headers = options.headers || {};
            $.ajax({
                url: constant.requestUrl + '?t=' + new Date().getTime(),
                dataType: 'json',
                headers: headers,
                method: 'get',
                success: function (data) {
                    if (data && data.code == 'A00000') {
                        callback.call(this, data);
                    } else {
                        console.log('get access fail.');
                        callback.call(this, data);
                    }
                },
                error: function (data) {
                    callback.call(this, data);
                }
            });
        }

        function qichuanUploadFile(options, callback) {
            var fileDetail = constant.file;
            fileDetail.file_id = options.data.file_id;
            var params = {
                url: constant.uploadUrl,
                file: fileDetail,
                headers: {
                    file_id: fileDetail.file_id,
                    file_size: fileDetail.size,
                    range: ('0' + '-' + (fileDetail.size - 1) + ''),
                    businessType: fileDetail.type.split("/")[0]
                }
            };
            var formData = new FormData();
            formData.append('businessType', params.headers['businessType']);
            formData.append('fileid', params.headers['file_id']);
            formData.append('imagefile', params.file);

            $.ajax({
                url: params.url,
                method: "post",
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (request) {
                    request.setRequestHeader("file_id", params.headers.file_id);
                    request.setRequestHeader("file_size", params.headers.file_size);
                    request.setRequestHeader("range", params.headers.range);
                    request.setRequestHeader("businessType", params.headers.businessType);
                },
                xhr: function () {        //这是关键  获取原生的xhr对象  做以前做的所有事情
                    var xhr = jQuery.ajaxSettings.xhr();
                    xhr.upload.onload = function () {
                        var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                        $imgdiv.remove();
                        //$('.button-manual').attr('disabled','disabled');
                        //$('input.uploadButton').attr('disabled','disabled');
                    }

                    xhr.upload.onprogress = function (ev) {
                        if (ev.lengthComputable) {
                            var percent = Math.floor(100 * ev.loaded / ev.total);
                            var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                            $imgdiv.find('div.bar').width(percent + '%');
                            if (percent == 100) {
                                $imgdiv.find('div.progress').remove();
                            }
                        }
                    }
                    return xhr;
                },
                data: formData,
                dataType: "json",
                success: function (data) {
                    if (data.code == "A00000") {
                        console.log("success upload");
                        callback.call(this, data);
                    }
                }
            })
        }


        function requestOver(data) {
            console.log("request file:" + data);
            if (data.code == 'A00000') {
                qichuanUploadFile(data, uploadOver);
            } else {
                console.log(data.msg);
            }
        }

        function uploadOver(data) {
            if (data.code == 'A00000') {

                $imgcrop.imagecrop("addImages", [
                    {url: data.data.httpInnerUrl, "spath": data.data["file_path"]}
                ]);
                var $uploadBtn = $imgcrop.find('input.uploadButton');
                $uploadBtn.val("");
            } else {
                console.log(data.msg);
            }
        }

        function doInit($target){
          //  var $imgcrop = $("#AlbumEditScreenCorp");
            $imgcrop = $target;
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $slideshow = $imgcrop.find('.slideshow');
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            $imgcrop.imagecrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            $uploadBtn.val("");
            $uploadBtn.bind("click", function (event) {
                console.log("click");
            })
            $uploadBtn.bind("change", function (event) {
                var file = $uploadBtn[0].files[0];
                var url = Com.file.getObjectURL(file)
                var checkFileType = Com.file.getExt(file.name);
                var acceptTypes = $uploadBtn[0].accept
                if (acceptTypes.indexOf("." + checkFileType) == -1) {
                    showTips({
                        content: "只允许提交类型为" + acceptTypes + "的文件",
                        type: "error"
                    })
                    return;
                }
                if (file.size > 1024 * 1024 * 5) {
                    showTips({
                        content: "上传文件大小不能超过5M",
                        type: "error"
                    })

                    return;
                }
                var headers = {
                    businessType: "image",
                    filesize: file.size,
                    role: "epg_image",
                    filetype: Com.file.getExt(file.name),
                    producttype: "ppc",
                    Location: "sh"
                }

                var options = {
                    headers: headers,
                    file: file
                };
                startUpload(file);
                qichuanRequestFile(options, requestOver);
            })
        }

        function initEditPicZone(){
            var picEnity = null;
            if (Program.Dao.cfgName.id == 0) {
                if (Program.Dao.cfgName.fatherId > 0) {
                    picEnity = Program.Dao.getChannel();
                    if (picEnity != null && picEnity.liveType != 2) {
                        picEnity = null;
                    }
                }
            } else {
                picEnity = Program.Dao.getProgram();
            }
            if (picEnity == null || picEnity.logoUrl == null || picEnity.logoUrl == "") {
                return;
            }
            var demoData = {"imageDatas": JSON.parse(picEnity.logoUrl) };
            if (demoData.imageDatas.length == 0) {
                return;
            }
            var materials = [];
            $.each(demoData.imageDatas[0].materials, function (index, element) {
                materials.push({url: element.url, spath: element.location, id: element.id, data: { id: element.id }});
            })
            var elementValue = {};
            $.each(demoData.imageDatas[0].images, function (index, element) {
                var plusData = {};
                var position = element.editInfo.cutPosition.split(",");
                elementValue[element.editInfo.scale.replace(":", "-")] = plusData;
                plusData.x1 = parseInt(position[0]);
                plusData.x2 = parseInt(position[0]) + parseInt(position[3]);
                plusData.y1 = parseInt(position[1]);
                plusData.y2 = parseInt(position[1]) + parseInt(position[2]);
                plusData.spath = element.materialLocation;
                $.each(demoData.imageDatas[0].materials, function (index, originalImg) {
                    if (element.materialLocation == originalImg.location) {
                        plusData.imgsrc = originalImg.url;
                        return false;
                    }
                })
                plusData.data = {};
            })
            $imgcrop.imagecrop("addImages", materials, function () {
                $imgcrop.imagecrop("setValue", elementValue);
            });
        }

        return {

            startUpload: startUpload,
            doInit:doInit,
            initEditPicZone:initEditPicZone
        }
    })()


});